from flask_restx import Resource
from flask import request
import pymysql
from models.database import get_db_connection
from api import ns
import traceback
import os
from utils.auth import token_required
from datetime import datetime

@ns.route('/history')
class HistoryList(Resource):
    @token_required
    def get(self):
        """获取用户的生成历史列表"""
        try:
            user_id = request.user.get('user_id')
            page = int(request.args.get('page', 1))
            per_page = int(request.args.get('per_page', 10))
            
            conn = get_db_connection()
            cursor = conn.cursor(pymysql.cursors.DictCursor)  # 使用字典游标
            
            # 获取总记录数
            cursor.execute("""
                SELECT COUNT(*) as total
                FROM history 
                WHERE user_id = %s
            """, (user_id,))
            total = cursor.fetchone()['total']
            
            # 获取分页数据
            cursor.execute("""
                SELECT 
                    history_id,
                    prompt_text,
                    style,
                    output_url,
                    created_at,
                    likes,
                    downloads
                FROM history
                WHERE user_id = %s
                ORDER BY created_at DESC
                LIMIT %s OFFSET %s
            """, (user_id, per_page, (page - 1) * per_page))
            
            records = []
            for row in cursor.fetchall():
                records.append({
                    'history_id': row['history_id'],
                    'text': row['prompt_text'],  # 前端使用 text
                    'style': row['style'],
                    'output_url': row['output_url'],
                    'created_at': row['created_at'].strftime('%Y-%m-%d %H:%M:%S'),
                    'likes': row['likes'],
                    'downloads': row['downloads']
                })
            
            return {
                'status': 'success',
                'data': {
                    'records': records,
                    'total': total,
                    'page': page,
                    'per_page': per_page,
                    'total_pages': (total + per_page - 1) // per_page
                }
            }
            
        except Exception as e:
            print(f"Error getting history list: {str(e)}")
            print("Error details:", traceback.format_exc())
            return {'status': 'error', 'message': '获取历史记录失败'}, 500
        
        finally:
            if conn:
                conn.close()

    @token_required
    def delete(self):
        """删除历史记录"""
        try:
            user_id = request.user.get('user_id')
            history_id = request.args.get('id')
            
            if not history_id:
                return {'status': 'error', 'message': '缺少记录ID'}, 400
            
            conn = get_db_connection()
            cursor = conn.cursor()
            
            # 删除记录
            cursor.execute("""
                DELETE FROM history 
                WHERE id = %s AND user_id = %s
                RETURNING output_url
            """, (history_id, user_id))
            
            result = cursor.fetchone()
            if result:
                # 可以选择同时删除本地文件
                output_url = result[0]
                if output_url.startswith('/static/outputs/'):
                    file_path = os.path.join(os.getcwd(), output_url.lstrip('/'))
                    if os.path.exists(file_path):
                        os.remove(file_path)
                
                conn.commit()
                return {'status': 'success', 'message': '删除成功'}
            else:
                return {'status': 'error', 'message': '记录不存在'}, 404
            
        except Exception as e:
            print(f"Error deleting history: {str(e)}")
            return {'status': 'error', 'message': '删除失败'}, 500
        
        finally:
            if conn:
                conn.close()

@ns.route('/history/<user_id>')
class UserHistory(Resource):
    @token_required
    def get(self, user_id):
        """获取用户的生成历史"""
        print('获取用户的生成历史', user_id)
        try:
            conn = get_db_connection()
            cursor = conn.cursor(pymysql.cursors.DictCursor)  # 使用字典游标
            print('获取用户的生成历史', conn)
            
            try:
                # 直接查询该用户的最近5条记录
                cursor.execute("""
                    SELECT
                        history_id,
                        prompt_text,
                        style,
                        output_url,
                        created_at,
                        likes,
                        downloads
                    FROM history
                    WHERE user_id = %s
                    ORDER BY created_at DESC
                    LIMIT 5
                """, (user_id,))
                
                records = cursor.fetchall()
                print('查询结果:', records)
                
                if not records:
                    return {
                        'status': 'error',
                        'message': '没有找到记录'
                    }, 404
                
                history = []
                for record in records:
                    history.append({
                        'history_id': record['history_id'],
                        'text': record['prompt_text'],  # 前端使用 text
                        'style': record['style'],
                        'output_url': record['output_url'],
                        'created_at': record['created_at'].strftime('%Y-%m-%d %H:%M:%S'),
                        'likes': record['likes'],
                        'downloads': record['downloads']
                    })
                
                return {
                    'status': 'success',
                    'data': {
                        'total': len(records),
                        'records': history
                    }
                }
                
            finally:
                cursor.close()
                conn.close()
                
        except Exception as e:
            print(f"Error getting history: {str(e)}")
            print("Error details:", traceback.format_exc())
            return {
                'status': 'error',
                'message': '获取历史记录失败'
            }, 500

# @ns.route('/historys/<history_id>')
class HistoryDetail(Resource):
    @token_required
    def get(self, history_id):
        """获取单个历史记录详情"""
        try:
            user_id = request.user.get('user_id')
            
            conn = get_db_connection()
            cursor = conn.cursor()
            
            # 获取指定记录 - 只用 user_id 做校验
            cursor.execute("""
                SELECT 
                    history_id,
                    prompt_text,
                    style,
                    output_url,
                    created_at,
                    likes,
                    downloads,
                    user_id  
                FROM history
                WHERE user_id = %s  
                ORDER BY created_at DESC
                LIMIT 5
            """, (user_id))
            
            records = cursor.fetchall()
            if not records:
                return {
                    'status': 'error',
                    'message': '没有找到记录'
                }, 404
            
            results = []
            for record in records:
                results.append({
                    'history_id': record[0],
                    'text': record[1],  # 前端仍使用 text
                    'style': record[2],
                    'output_url': record[3],
                    'created_at': record[4].strftime('%Y-%m-%d %H:%M:%S'),
                    'likes': record[5],
                    'downloads': record[6],
                    'user_id': record[7]  # 返回 user_id
                })
            
            return {
                'status': 'success',
                'data': results
            }
            
        except Exception as e:
            print(f"Error getting history detail: {str(e)}")
            print("Error details:", traceback.format_exc())
            return {'status': 'error', 'message': '获取记录详情失败'}, 500
        
        finally:
            if conn:
                conn.close() 